package Java_Lab.Multithreading.MergeSort;

public class MergeSort implements Runnable{
    volatile int[] A;
    volatile int p, r;

    public static void main(String[] str) throws InterruptedException {
        int[] a = {12,45,21,65,8,14,21,32};
        MergeSort mergeSort = new MergeSort(a,0,a.length-1);
        Thread thread = new Thread(mergeSort);
        thread.start();
        
        Thread.sleep(1000L);
        
        for(int i = 0; i < a.length; i++){
            System.out.print(a[i] + " ");
        }
    }

    MergeSort(int[] A, int p, int r){
        this.A = A;
        this.p = p;
        this.r = r;
    }

    public void run() {
        if(p < r){
            int q = (p+r)/2;
            Thread thread1 = new Thread(new MergeSort(A,p,q));
            Thread thread2 = new Thread(new MergeSort(A, q+1, r));
            thread1.start();
            thread2.start();

            merge(A,p,q,r);
        }
    }

    void merge(int[] A, int p, int q, int r){
        int n1 = q-p+1;
        int n2 = r-q;
        int[] L = new int[n1+1];
        int[] R = new int[n2+1];
        int i,j;
        for(i = 0; i < n1; i++){
            L[i] = A[p+i];
            System.out.println(Thread.currentThread().getName() + " L cp");
        }
        for(j = 0; j < n2; j++){
            R[j] = A[q+j+1];
            System.out.println(Thread.currentThread().getName() + " R cp");
        }
        L[n1] = Integer.MAX_VALUE;
        R[n2] = Integer.MAX_VALUE;
        i = j = 0;
        for(int k = p; k <= r; k++){
            if(L[i] <= R[j]){
                A[k] = L[i];
                i++;
            }else{
                A[k] = R[j];
                j++;
            }
        }
    }
}